package com.hfzy.ihk.web.linkcall.support.aop;

import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.web.linkcall.context.Context;
import com.hfzy.ihk.web.linkcall.context.ContextKey;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class ReceiveUserPrivParamHandle {
    private static final Logger logger = LoggerFactory.getLogger(ReceiveUserPrivParamHandle.class);

    //切入 到 引用注解 的方法中
    @Pointcut("@annotation(com.hfzy.ihk.web.linkcall.support.annotation.ReceiveUserPrivParam)")
    public void pointCutFun(){};

    @Before(value = "pointCutFun()")
    void pointCutFunBefore(JoinPoint point){
        logger.debug("接收并处理用户权限信息");
        try{
            if(Context.contextIntf!=null){
                HttpServletRequest httpServletRequest = Context.contextIntf.getRequest();
                //到时可以通过加密来进行处理传递的参数信息
                if(httpServletRequest!=null){
                    String createUserId = httpServletRequest.getParameter("createUserId");
                    if(!Utils.isNullString(createUserId) && !"0".equals(createUserId)){
                        if(Context.get(ContextKey.CURRENT_USER_ID)==null){
                            Context.set(ContextKey.CURRENT_USER_ID,Long.parseLong(createUserId));
                        }else if(!createUserId.equals(Context.get(ContextKey.CURRENT_USER_ID).toString())){ //如果判断是不一致时， 进行替换
                            Context.set(ContextKey.CURRENT_USER_ID,Long.parseLong(createUserId));
                        }
                    }
                    String canSearchAll = httpServletRequest.getParameter("canSearchAll");
                    //如果可以查全部时，移除限定的userId 进行查询
                    if(!Utils.isNullString(canSearchAll) && ("true".equals(canSearchAll) || "false".equals(canSearchAll))){
                        if(Context.get(ContextKey.CAN_SEARCH_ALL)==null){
                            Context.set(ContextKey.CAN_SEARCH_ALL,Boolean.parseBoolean(canSearchAll));
                        }else if(!canSearchAll.equals(Context.get(ContextKey.CAN_SEARCH_ALL).toString())){ //如果判断是不一致时， 进行替换
                            Context.set(ContextKey.CAN_SEARCH_ALL,Boolean.parseBoolean(canSearchAll));
                        }
                    }
                }
            }
        }catch (Exception e){
           logger.error("接收并处理用户权限信息异常==="+e.getMessage());
        }
    }
}
